package algorithmTopics.link;

import java.util.Arrays;

public class test2 {


    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        listNode.next = listNode1;
        ListNode listNode2 = new ListNode(3);
        listNode1.next = listNode2;
        System.out.println(Arrays.toString(printLink(listNode, null)));

        test2 test2 = new test2();

        System.out.println(Arrays.toString(printLink(test2.removeNthFromEnd(listNode,3), null)));
    }




    public static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        //获取长度
        int linkLen = getLinkLen(head) - n;
        //删除头节点
        if (linkLen == 0) {
            return head.next;
        }
        //需要删除节点的前一位
        ListNode node = head;
        for (int i = 0; i < linkLen - 1; i++) {
            node = node.next;
        }
        node.next = node.next.next;
        return head;
    }

    public int getLinkLen(ListNode head) {
        if (head.next == null) {
            return 1;
        }
        int i = getLinkLen(head.next);
        return  i + 1;
    }

    public static int[] printLink(ListNode head , int[] list ) {
        if (head.next == null) {
            return new int[] {head.val};
        }
        int[] ints = printLink(head.next, null);
        //结果集合
        int[] res = new int[ints.length + 1];
        System.arraycopy(ints,0,res,0,ints.length);
        res[ints.length] = head.val;
        return res;

    }
}
